<?php
class Response
{
    const RETURN_REDIRECT   = 'redirect';
    const RETURN_JON        = 'json';
    const RETURN_HTML       = 'html';

    protected $_returnType = self::RETURN_HTML;

    /**
     * @var Template
     */
    protected $_template = null;

    protected $_redirectUrl = '';

    protected $_headers = array();
    protected $_content = '';

    public function addHeader($name, $value)
    {
        $this->_headers[$name] = $value;
    }

    public function setReturnType($returnType)
    {
        switch ($returnType)
        {
            case self::RETURN_REDIRECT:
                $this->addHeader('Location', $this->_redirectUrl);
                break;
            case self::RETURN_JON:
                $this->addHeader('Cache-Control', 'no-cache, must-revalidate');
                $this->addHeader('Expires: Mon', '26 Jul 1997 05:00:00 GMT');
                $this->addHeader('Content-type', 'application/json');
                break;
        }
    }

    public function setRedirectUrl($redirectUrl)
    {
        if (!preg_match('/^http:\/\//', $redirectUrl))
        {
            $indexFile = ($indexFile = Config::get('front_file'))? $indexFile . '/' : '';

            $redirectUrl = Config::get('base_href') . $indexFile . $redirectUrl;
        }

        $this->_redirectUrl = $redirectUrl;
    }

    public function setTemplate(Template $template)
    {
        $this->_template = $template;
        $this->_content = $template->fetchContent();
    }

    public function getTemplate()
    {
        return $this->_template;
    }

    public function setContent($content)
    {
        $this->_content = $content;
    }

    public function getContent()
    {
        return $this->_content;
    }

    public function sendHeaders()
    {
        if (!headers_sent())
        {
            foreach ($this->_headers as $header => $value)
            {
                header($header . ':' . $value);
            }
        }
        else
        {
            throw new MyException('Error: Header sent!');
        }
    }

    public function output()
    {
        if ($this->_returnType == self::RETURN_JON)
        {
            echo json_encode($this->_template->params);
        }
        else if ($this->_returnType == self::RETURN_HTML)
        {
            echo $this->_content;
        }
    }
}